<?php
class Redirect {
    private $url = '';
    private $message = '';
    private $delay = 1;
    private $template = false;
    private $alert = '
        <script type="text/javascript">
            alert("%s");
            %s.location="%s";
        </script>';
    private $confirm = '
        <script type="text/javascript">
            if(confirm("%s")) {
                location="%s";
            } else {
                location="%s";
            }
        </script>';
    private $redirect = '
        <html>
            <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
            <meta http-equiv="refresh" content="%d; url=%s" />
            </head>
            <body>
            %s
            </body>
        </html>';
    private $returnContents = '';

    public function __construct($action, $module=MODULE_NAME, $args=array(), $message='', $delay=0) {
        $this->url = Url::getUrl($action, $module, $args);
        if ('' != $message) $this->message = $message;
        $this->assign('url', $this->url);
        $this->assign('message', $message);
        if (0 != $delay) $this->delay = $delay;
        $this->assign('delay', $delay);
    }

    public function setTemplate($template, $tplDir = MODULE_NAME) {
        $this->template = true;
        View::setTemplate($template, $tplDir);
    }
    
    public function assign($var, $value='') {
        View::assign($var, $value);
    }

    public function jsAlert($message = '', $target='self') {
        $message = $message ? $message : $this->message;
        $message = $message ? $message : '操作执行成功';
        $this->message = $message;
        $this->returnContents = sprintf($this->alert, addslashes($message), $target, $this->url);

    }

    public function jsConfirm($falseAction, $falseModule=MODULE_NAME, $falseArgs=array(), $message='') {
        $url = Url::getUrl($falseAction, $falseModule, $falseArgs);
        $message = $message ? $message : $this->message;
        $message = $message ? $message : '确定执行本次操作吗？';
        $this->message = $message;
        $this->returnContents = sprintf($this->confirm, addslashes($message), $this->url, $url);
    }

    public function run() {
        if ($this->template) {
            echo View::fetch();
        } else if ($this->returnContents){
            echo $this->returnContents;
        } else {
            if ($this->message) {
                echo sprintf($this->redirect, $this->delay, $this->url, $this->message);
            } else {
                header("location:" . $this->url);
            }
        }
        exit;
    }
};
?>